//
//  GatheringDetailViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/12/10.
//  Copyright © 2015年 reabam.com. All rights reserved.
//

#import "PayForSuccessViewController.h"
#import "RDVTabBarController.h"
#import "UIViewExt.h"
#import "HttpRequest.h"
#import "RDVTabBarController.h"
#import "UIButton+WebCache.h"
#import "OrderDetailViewController.h"
#import "MemberCardRecordsViewController.h"
#import "AddMemberViewController.h"
//#import "ServiceDetailViewController.h"
#import "PrinterListViewController.h"
@interface PayForSuccessViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate,UIScrollViewDelegate,BluetoothDelegate>
@end

@implementation PayForSuccessViewController

{
    NSMutableArray*deviceList;
    NSDictionary*dataDict;
}
@synthesize alt = alt;


-(void)BackAction:(UIButton *)sender{
    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0] animated:YES];
}
- (void)viewDidDisappear:(BOOL)animated
{
    
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [PrinterWraper SetBlutoothDelegate:self];
    [PrinterWraper StartScanTimeout:10];
    
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [PrinterWraper StopScan];
    [PrinterWraper SetBlutoothDelegate:nil];
    
}

-(void)Printer:(NSString *)str{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:self.orderId forKey:@"orderId"];
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    [HttpRequest requestData:@"Business/Order/Detail" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            NSLog(@"-----------%@", severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                dataDict=severDataDict.dataDict;
                [self Printe];
            }else{
                [Global hideProgressHUDInternal:self.view];
                [Global showTextHudSub:severDataDict.resultStr view:self.view];
            }
        }else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:severDataDict.resultStr view:self.view];
        }
    }];
    
}
-(void)updateBluetoothDevice:(NSMutableArray*)devices;
{
    deviceList=[[NSMutableArray alloc]init];
    deviceList  =devices;
    NSLog(@"-----%@",deviceList);
}
-(void)BlueToothOpen:(BOOL)isopen;{
    deviceList=nil;
}
-(void)Printe{
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Device = [user objectForKey:@"Device"];
    if (deviceList.count>0) {
     
        if (Device.length>0) {
            
            
            //*****************************************************//
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:1 rotation:0];// 3 大字体  ，7默认行间距,1局中对齐
            [PrinterWraper addPrintText:@"欢迎光临\n\n"];//打印文字
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            [PrinterWraper addPrintText:[NSString stringWithFormat: @"收银员: %@  \n", [[dataDict objectForKey:@"order"] objectForKey:@"source"] ]];
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            [PrinterWraper addPrintText:[NSString stringWithFormat: @"收款时间: %@  \n", [[dataDict objectForKey:@"order"] objectForKey:@"orderDate"] ]];
            
            NSDictionary *value = [dataDict objectForKey:@"member"];
            //           NSLog(@"---%ld",value.count);
            if (value.count==0)//零售会员
            {
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat: @"会员名称: %@  \n", @"零售会员" ]];
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat: @"会员卡号: %@  \n", @"--------"]];
            }else{
                
                
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat: @"会员名称: %@  \n", [[dataDict objectForKey:@"member"] objectForKey:@"memberName"] ]];
                
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                if (    [[Global getJudgeTheErrorStr:[[dataDict objectForKey:@"member"] objectForKey:@"cardNo"]]isEqualToString:@""]
                    ||[[dataDict objectForKey:@"member"] objectForKey:@"cardNo"]==NULL) {
                    [PrinterWraper addPrintText:[NSString stringWithFormat: @"会员卡号: %@  \n", @""]];
                    
                }else{
                    [PrinterWraper addPrintText:[NSString stringWithFormat: @"会员卡号: %@  \n", [[dataDict objectForKey:@"member"] objectForKey:@"cardNo"] ]];
                }
            }
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            [PrinterWraper addPrintText:[NSString stringWithFormat: @"门店名称: %@  \n", [[dataDict objectForKey:@"order"] objectForKey:@"companyName"] ]];
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            
 
            [PrinterWraper addPrintText:[NSString stringWithFormat: @"客服电话: %@  \n", [[dataDict objectForKey:@"companyBaseInfo"] objectForKey:@"phone"] ]];
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];

            
            
            [PrinterWraper addPrintText:@"--------------------------------\n\n"];
            
            
            for (NSDictionary* dicc in  [dataDict objectForKey:@"orderItem"] )
            {
                if ([[NSString stringWithFormat:@"%@",[dataDict valueForKey:@"receiptTemplate"]] isEqualToString:@"TemplateB"]) {
                    [PrinterWraper setPrintFormat:0 LineSpace:1 alinment:0 rotation:0];
                    [PrinterWraper addPrintBarcode:[NSString stringWithFormat:@"%@",[dicc valueForKey:@"skuBarcode"]] isTwoDimensionalCode:0];//1维码
                    
                }else{
                    
                }
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat:@"%@\n",[dicc valueForKey:@"itemName"]]];
                
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:2 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat:@"%@x%@   小计：%@\n",[dicc valueForKey:@"dealPrice"],[dicc valueForKey:@"quantity"],[dicc valueForKey:@"totalMoney"]]];
                [PrinterWraper addPrintText:@"\n"];//打印文字
                
            }
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            
            [PrinterWraper addPrintText:@"--------------------------------\n\n"];
            
            
            
//            //  NSArray *headers =@[@"商品名称",@"单价",@"小计"];
//            NSMutableArray*MutableArray1=[[NSMutableArray alloc]init];
//            
//            for (NSDictionary* dicc in  [dataDict objectForKey:@"orderItem"] )
//            {
//                [MutableArray1 addObject:[NSString stringWithFormat:@"%@\n",[dicc valueForKey:@"itemName"]]];
//                [MutableArray1 addObject:[NSString stringWithFormat:@"%@x%@",[dicc valueForKey:@"dealPrice"],[dicc valueForKey:@"quantity"]]];
//                [MutableArray1 addObject:[NSString stringWithFormat:@"   小计：%@\n",[dicc valueForKey:@"totalMoney"]]];
//                
//            }
//            
//            NSArray* body =@[MutableArray1];
//            //打印商品列表，会自动排版，要求数组长度一致，空白地方用@""
//            
//            [PrinterWraper addItemLines:body];
//            
//            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
//            
//            [PrinterWraper addPrintText:@"--------------------------------\n\n"];
//            
            
            
            
            NSNumber*Total = [[dataDict objectForKey:@"order"] objectForKey:@"totalMoney"];
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setPositiveFormat:@"###,##0.00;"];
            NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:Total.doubleValue]];
            
            NSNumber*orderPreferentia = [[dataDict objectForKey:@"order"] objectForKey:@"preferentialMoney"];
            NSString *formattedNumberString1 = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:orderPreferentia.doubleValue]];
            
            NSNumber*discount = [[dataDict objectForKey:@"order"] objectForKey:@"discountMoney"];
            NSString *formattedNumberString2 = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:discount.doubleValue]];
            
            NSNumber*freight = [[dataDict objectForKey:@"order"] objectForKey:@"expressFee"];
            NSString *formattedNumberString3 = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:freight.doubleValue]];
            
            NSNumber*preferential = [[dataDict objectForKey:@"order"] objectForKey:@"couponMoney"];
            NSString *formattedNumberString4 = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:preferential.doubleValue]];
            
            NSNumber*realMoney = [[dataDict objectForKey:@"order"] objectForKey:@"realMoney"];
            NSString *formattedNumberString5 = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:realMoney.doubleValue]];
            
            
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            [PrinterWraper addPrintText:[NSString stringWithFormat: @"商品总额: %@  \n",formattedNumberString ]];
            
            
            if ([formattedNumberString1 isEqualToString:@"0.00"]) {
                
            }else{
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat: @"活动优惠: %@  \n",formattedNumberString1 ]];
            }
            
            if ([formattedNumberString2 isEqualToString:@"0.00"]) {
                
            }else{
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat: @"抹零折扣: %@  \n",formattedNumberString2 ]];
            }
            if ([formattedNumberString3 isEqualToString:@"0.00"]) {
                
            }else{
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat: @"运费: %@  \n",formattedNumberString3 ]];
            }
            
            if ([formattedNumberString4 isEqualToString:@"0.00"]) {
                
            }else{
                [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
                [PrinterWraper addPrintText:[NSString stringWithFormat: @"优惠券: %@  \n",formattedNumberString4 ]];
            }
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            [PrinterWraper addPrintText:[NSString stringWithFormat: @"实付款: %@  \n",formattedNumberString5 ]];
            
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            [PrinterWraper addPrintText:[NSString stringWithFormat: @"支付方式: %@  \n",[[dataDict objectForKey:@"order"] objectForKey:@"payTypeName"] ]];
            
            [PrinterWraper setPrintFormat:1 LineSpace:58 alinment:0 rotation:0];
            [PrinterWraper addPrintText:@"--------------------------------\n\n"];
            
            [PrinterWraper setPrintFormat:1 LineSpace:7 alinment:0 rotation:0];
            [PrinterWraper addPrintText:@"谢谢光临，欢迎下次惠顾\n"];
            
            [PrinterWraper addPrintText:@"\n\n"];
            
            [PrinterWraper connectPrinter:Device shouldreset:YES];
            //*****************************************************//
            
        }else{
            
            PrinterListViewController *detail=[[PrinterListViewController alloc] init];
            detail.Dic=dataDict;
            [self.navigationController pushViewController:detail animated:YES];
            
        }
    }else{
    
      [self showAlertMessage:@"蓝牙未开!"];
    }
}
-(void)didConnected:(NSString*)deviceUid  Result:(BOOL)success;{
    //    [SVProgressHUD dismiss];
    
    if (success)
        
        [self excuteTask];
    
}
-(void)excuteTask{
    [PrinterWraper startPrint:nil];
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavi];
    self.view.backgroundColor=[UIColor whiteColor];
    
//    NSString *str1=[NSString stringWithFormat:@"%d",TARGET_VERSION];
//    if ([str1 isEqualToString:@"4"]||[str1 isEqualToString:@"14"]) {
//        
//        
//    }else{
    UIButton* Printer=[[UIButton alloc]initWithFrame:CGRectMake(0, 12.5,70, 28)];
    [ Printer setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
    [ Printer setTitle:@"打印小票" forState:UIControlStateNormal];
    Printer. titleLabel.font=[UIFont systemFontOfSize:14];
    [ Printer setTitleColor:luseColor forState:UIControlStateNormal];
    
    [Printer addTarget:self action:@selector(Printer:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* myBtnBtn = [[UIBarButtonItem alloc] initWithCustomView:Printer];
    self.navigationItem.rightBarButtonItem = myBtnBtn;
//    }
    
    
    UIImageView *gou = [[UIImageView alloc]initWithFrame:CGRectMake(ScreenWidth/2-15,60+64, 30, 30)];
    gou.image=[UIImage imageNamed:@"gous"];
    [self.view addSubview:gou];
    UILabel *payAmountLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,130+64, ScreenWidth, 30)];
    payAmountLabel.font=[UIFont systemFontOfSize:25];
    payAmountLabel.textAlignment=NSTextAlignmentCenter;
    NSString*GoldPrice=[NSString stringWithFormat:@"%@",self.payAmount];
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setPositiveFormat:@"###,##0.00;"];
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:GoldPrice.floatValue]];
    payAmountLabel.text=[NSString stringWithFormat:@"¥ %@",formattedNumberString];
    
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"¥ %@" ,formattedNumberString]];
    
    [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:23.0]
     
                          range:NSMakeRange(0, 1)];
    
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:backColor
                          range:NSMakeRange(0, 1)];
    payAmountLabel.attributedText = AttributedStr;
    
    [self.view addSubview:payAmountLabel];
    
    UILabel* PayLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 160+64, ScreenWidth,13.0)];
    PayLabel .text=@"交易支付成功" ;
    PayLabel.textColor=shenhuiColor;
    PayLabel.textAlignment=NSTextAlignmentCenter;
    PayLabel.font = [UIFont systemFontOfSize: 13.0];
    [self.view addSubview:PayLabel];
    
    
    UIButton* ToObtain = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth/2-60, 225+64, 120,36)];
    if ([self.orderType isEqualToString:@"order"]) {
        [ToObtain setTitle:@"查看订单详情" forState:UIControlStateNormal];
    }
    
    if ([self.orderType isEqualToString:@"service"]) {
        
        [ToObtain setTitle:@"查看服务详情" forState:UIControlStateNormal];
    }
    ToObtain.titleLabel.font = [UIFont systemFontOfSize: 13.0];
    [ToObtain.layer setCornerRadius:2.0]; //设置矩圆角半径
    [ToObtain.layer setBorderWidth:0.5];   //边框宽度
    CGColorSpaceRef tureBTnSpace = CGColorSpaceCreateDeviceRGB();
    CGColorRef tureBTncolorref = CGColorCreate(tureBTnSpace,(CGFloat[]){90/255.0, 130/255.0, 26/255.0, 1.0});
    [ToObtain.layer setBorderColor:tureBTncolorref];//边框颜色
    [ToObtain setTitleColor:luseColor
                   forState:UIControlStateNormal];
    [ToObtain addTarget:self action:@selector(ToObtain:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:ToObtain];
    NSLog(@"---%@",self.memberId);
    
    if ([self.orderType isEqualToString:@"card"]) {
        [ToObtain setTitle:@"查看储值详情" forState:UIControlStateNormal];
    }else{
        if (self.memberId.length>0) {
            
        }else{
            UIButton* addMember = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth/2-70,ScreenHeight-80, 130,15)];
            [addMember setTitle:@"添加顾客为会员" forState:UIControlStateNormal];
            addMember.titleLabel.font = [UIFont systemFontOfSize: 15.0];
            [addMember setTitleColor:luseColor
                            forState:UIControlStateNormal];
            [addMember addTarget:self action:@selector(addMember:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:addMember];
            
            UIButton*jiantou = [[UIButton alloc]init];
            jiantou.frame = CGRectMake(addMember.right,ScreenHeight-90, 33, 33);
            [jiantou setImage:[UIImage imageNamed:@"shouqi"] forState:UIControlStateNormal];
            [jiantou addTarget:self action:@selector(addMember:) forControlEvents:UIControlEventTouchUpInside];
            [self.view addSubview:jiantou];}
    }
    
    
    
    
}

-(void)addMember:(UIButton*)sender
{
    AddMemberViewController *detailViewController = [[AddMemberViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];
    
    
    
}
-(void)ToObtain:(UIButton*)sender{
    if ([self.orderType isEqualToString:@"card"]) {
        MemberCardRecordsViewController *detailViewController = [[MemberCardRecordsViewController alloc] init];
        detailViewController.memberId=self.memberId;
        [self.navigationController pushViewController:detailViewController animated:YES];
    }
    if ([self.orderType isEqualToString:@"order"]) {
        OrderDetailViewController *detailViewController = [[OrderDetailViewController alloc] init];
        detailViewController.orderId=self.orderId;
        [self.navigationController pushViewController:detailViewController animated:YES];
    }
//    if ([self.orderType isEqualToString:@"service"]) {
//        
//        ServiceDetailViewController *detailViewController = [[ServiceDetailViewController alloc] init];
//        detailViewController.orderId=self.orderId;
//        [self.navigationController pushViewController:detailViewController animated:YES];
//        
//    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)setNavi{
    [[self rdv_tabBarController] setTabBarHidden:YES];
    
    self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    
    self.title=@"支付成功";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    self.navigationController.navigationBarHidden = NO;
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage =[[UIImage alloc] init];
    
    
    
    
}
- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
